package com.atguigu.e_reflect.method;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Demo1 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        //反射第一步 : 获取类的字节码对象
        Class<?> clazz = Class.forName("com.atguigu.e_reflect.method.Student");

        //快速获取一个学生对象
        Student student = (Student) clazz.newInstance();


        //获取sleep方法对象
        Method sleep = clazz.getDeclaredMethod("sleep");
        System.out.println("sleep = " + sleep);
        //启动方法
        //Object obj1 = sleep.invoke(学生对象, 实参);//obj1 : 接收sleep方法的返回值
        Object obj1 = sleep.invoke(student);//obj1 : 接收sleep方法的返回值
        System.out.println("obj1 = " + obj1); // sleep方法无返回值, invoke方法的返回值 null
        System.out.println("----------------------------");

        Method eat = clazz.getDeclaredMethod("eat", String.class);
        System.out.println("eat = " + eat);

        Object obj2 = eat.invoke(student, "汉堡包");
        System.out.println("obj2 = " + obj2);//null

        System.out.println("----------------------------");

        Method study = clazz.getDeclaredMethod("study");
        System.out.println("study = " + study);

        Object obj3 = study.invoke(student);
        System.out.println("obj3 = " + obj3);

        System.out.println("----------------------------");

        Method playGame = clazz.getDeclaredMethod("playGame", String.class, int.class);
        System.out.println("playGame = " + playGame);

        //没有权限的在使用之前 开启暴力反射开关
        playGame.setAccessible(true);

        Object obj4 = playGame.invoke(student, "LOL", 8);
        System.out.println("obj4 = " + obj4);//"小明玩 " + LOL + " 玩了 " + 8 + " 小时! ";

        System.out.println("----------------------------");


    }
}
